package com.xmg.dataStructure.tensuanfa;

/**
 * 非递归的二分查找算法
 */
public class BinarySearchNoRecur {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,34,56,234,999};
        int index = binarySearch(arr,34);
        System.out.println("index = " + index);
    }

    public static int binarySearch(int[] arr,int target){
        int left = 0;
        int right = arr.length-1;
        while (left<=right){
            int mid = (left+right)/2;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid]>target){//向左查找
                right = mid -1;
            }else{
                left = mid + 1;
            }
        }
        return -1;
    }
}
